# -*- coding: utf-8 -*-
# @Time    : 2019-12-11 20:54
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : R12_IC_TradeTypeCheck_WHB_2D.py
# @Software: PyCharm


'''eof
name:特殊交易类型校验
code:R12_IC_TradeTypeCheck_WHB_2D
tableName:
columnName:
groups:弱规则>个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import re
import datetime
import pandas as pd
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return ""
        elif table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def R12_IC_TradeTypeCheck_WHB_2D():
    data = IC_DSJ_2D['data']
    factor = []
    # 借贷账户信息
    PDA = getTable(data, 'PDA', 1)
    if PDA is None:
        return u'缺失值'
    elif PDA == "":
        return 0
    else:
        # 借贷账户信息单元
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return u'缺失值'
        elif PD01 == [{}]:
            return 0
        else:
            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    # 特殊交易信息段
                    PD01F = getTable(i, 'PD01F', 0)
                    if PD01A is None or PD01A == "" or PD01F is None or PD01F == "":
                        factor.append(None)
                    elif PD01F == [{}]:
                        factor.append(0)
                    else:
                        # 账户类型
                        PD01AD01 = PD01A[0].get('PD01AD01')
                        # 特殊交易信息
                        PD01FH = getTable(PD01F[0], 'PD01FH', 1)
                        if PD01AD01 in null_type_list or PD01FH is None or PD01FH == "":
                            factor.append(None)
                        else:
                            # D1(非循环贷账户),R1(循环贷账户),R4(循环额度下分账户)
                            if PD01AD01 == 'D1' or PD01AD01 == 'R1' or PD01AD01 == 'R4':
                                for PD01FH_Items in PD01FH:
                                    try:
                                        # 特殊交易发生日期
                                        PD01FR01 = Formate(PD01FH_Items.get('PD01FR01'))
                                        PD01FR01_In = (datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=5)).strftime('%Y%m%d')
                                        if PD01FR01 in null_type_list:
                                            factor.append(None)
                                        elif PD01FR01 <= PD01FR01_In:
                                            factor.append(0)
                                        else:
                                            # 特殊交易类型
                                            PD01FD01 = PD01FH_Items.get('PD01FD01')
                                            PD01FR01 = PD01FH_Items.get('PD01FR01')
                                            try:
                                                # month =PD01FR01[0:7]
                                                month = int(Formate(PD01FR01))
                                            except:
                                                month =0
                                            if PD01FD01 in null_type_list:
                                                factor.append(None)
                                            # 【1-展期，2-担保人（第三方）代偿，3-以资抵债，6-强制平仓未结清，8-司法追偿，12-资产剥离，13-资产转让，11-债务减免，16-银行主动延期，17-强制平仓，14-信用卡个性化分期】
                                            elif PD01FD01 in ['2', '3','6','8','12','13','11','17','14']:
                                                factor.append(1)
                                            # elif PD01FD01 in ['1','16'] and month not in ['2020-02','2020-03','2020-04','2020-05','2020-06','2020-07','2020-08','2020-09','2020-10','2020-11','2020-12','2021-01','2021-02','2021-03','2021-04','2021-05','2021-06','2021-07','2021-08','2021-09','2021-10','2021-11','2021-12']:
                                            elif PD01FD01 in ['1', '16'] and (month < 20200125 or month > 20211231):
                                                factor.append(1)
                                            else:
                                                factor.append(0)
                                    except:
                                        factor.append(None)
                                        continue
                            else:
                                factor.append(0)
                except:
                    factor.append(None)
                    continue

    factorNotNone = filter(lambda x: x is not None, factor)
    if len(factorNotNone) == 0:
        return u'缺失值'
    else:
        return sum(factorNotNone)

result = R12_IC_TradeTypeCheck_WHB_2D()
if __name__ == '__main__':
    import json
    with open(r'C:\Users\john\Desktop\samples\data.json') as ff:
        dd = json.loads(ff.read())
    IC_DSJ_2D = dd['IC_DSJ_2D']
    result = R12_IC_TradeTypeCheck_WHB_2D()
    print(result)
